<?php
/*
This is application controller, the main controller
*/
include 'view/view.php';

class appController extends appView
{
	var $method;
	var $data;
	
	//this is for file handling request
	var $file;
	
	//Model object
	var $model;
	
	//plugins array
	var $api = array();
	
	//appliaction path
	var $appPath = '';
	
	//protected pages
	var $protectedPages = array();
	
	var $totalRows = 20;
	
	
	function __construct()
	{
		parent::__construct();
	}
	
	
	function callMethod()
	{
		$func = $this->method;
		$this -> ${func}();
	}
	
	//This function is loading methods which need to be loaded on every page, see diaptcher line 72
	function preLoadMethods($methods)
	{
		foreach($methods as $m)
		{
			$func = $m;
			$this -> ${func}();
		}
		
	}
	
	
	/*
	This functino setting the variables
	*/
	
	function set($param1, $param2 = '')
	{
		$this -> viewVars[$param1] = $param2;
	}
	
	
	/*
	loading plugins
	*/
	function loadAPIs()
	{
		foreach($this -> api as $key => $value):	
			$srcScript = "api/".$value['dir'].$value['script'];
			echo '<script type="text/javascript" src="'.$srcScript.'">';
			echo '</script>';
			
			//check is style exists
			if($value['style']):
				$srcStyle = "api/".$value['dir'].$value['style'];
				echo '<link href="'.$srcStyle.'" rel="stylesheet" type="text/css" />';
			endif;
		endforeach;
	}
	
	/*
	redirecting the page
	*/
	function redirect($param)
	{
		$url = '?';
		if(is_array($param))
		{
			foreach($param as $key => $value)
			{
				$url .= $key.'='.$value.'&';	
			}
			$url = substr($url, 0, -1);
		}
		else
		{
			$url = '?page='.$param;
		}
		
		
		
		header("LOCATION: ".$url);
		//return $url;
	}
	
	/*
	protect pages
	*/
	function protect($page)
	{
		if(!isset($_COOKIE['adminid_gosell']) and in_array($page, $this -> protectedPages))
		{
			$redirectTo = array('page'	=>	'adminLogin',
								'sub'	=>	'bad');
			$this -> redirect($redirectTo);
		}
	}
	
	/*
	This function is upload files
	*/
	function uploadFile($file, $path, $prefix = null, $existing = null)
	{
		include_once 'inc/Upload.php';
		
		$UpLoader = new _Uploader();
		$Exts = array("jpg","jpeg", "gif", "png");
		$UpLoader -> SetAllowedExts($Exts);
		
		$UpLoader->SetFile($file);
		$UpLoader -> SetPath($path);
		
		if($existing != null)
		{
			$UpLoader -> DeleteFile($existing);		//Deleting existing picture from directory
			//$UpLoader -> SetPath($path."thumb/");
			//$UpLoader -> DeleteFile($existing);		//Deleting existing picture from directory
		}
			
		
		//echo 'file size '.$UpLoader->Size;
		
		if($UpLoader->Size < 1000000)
		{
			//echo 'existing pic name '.$existing;
				$UpLoader -> SetPath($path);
				$UpLoader -> SetName($prefix.'-'.time());
				$UpLoader -> Upload();
				
				//for Thumb
				/*$UpLoader -> SetPath($path."thumb/");
				$UpLoader -> UploadReSize(125,125);*/
				
				$pictureNewName = $UpLoader -> FileName;
				
				return $pictureNewName;
						
		}
		else
		{	
			return 'FE';		//File error $UpLoader->Size;
		}
	}
	
	
	function unloadFile($file, $path)
	{
	include_once 'inc/Upload.php';
	global $dm;
		
	$UpLoader = new _Uploader();
	//$Exts = array("jpg","jpeg", "gif", "png");
	//$UpLoader -> SetAllowedExts($Exts);
	
	$UpLoader->SetFile($file);
	$UpLoader -> SetPath($path);
	
		$UpLoader -> DeleteFile($file);		//Deleting existing picture from directory
		//$UpLoader -> SetPath($path."thumb/");
		//$UpLoader -> DeleteFile($file);		//Deleting existing picture from directory
		
	}
	
	
	/**
	 * Load Helper
	 *
	 * This function loads the specified helper file.
	 *
	 * @access	public
	 * @param	mixed
	 * @return	void
	 */
	function loadHelper($helpers = array())
	{
		foreach ($helpers as $helper)
		{
			$helper = $helper.'_helper';
			if (file_exists($this -> appPath.'inc/helpers/'.$helper.'.php'))
			{
				include_once($this -> appPath.'inc/helpers/'.$helper.'.php');
				return true;
			}
			else
			{
				die('Unable to load the requested file: '.$this -> appPath.'inc/helpers/'.$helper);
			}
		}
	}
	
	/*
	This is to load classes.
	*/
	function loadClass($class_name, $obj='')
	{
		if (file_exists($this -> appPath.'inc/classes/'.$class_name.'.php'))
		{
			include_once($this -> appPath.'inc/classes/'.$class_name.'.php');
			
			include_once($this -> appPath.'inc/classes/'.$class_name.'.php');
			$this -> ${obj} = new ${class_name};
		}
		else
		{
			die('Unable to load the requested file: '.$this -> appPath.'inc/classes/'.$class_name.'.php');
		}
	}
	
	/*
	This function is generating password string
	*/
	
	function generatePassword($length=6, $strength=0) 
	{
		$vowels = 'aeuy';
		$consonants = 'bdghjmnpqrstvz';
		if ($strength & 1) {
			$consonants .= 'BDGHJLMNPQRSTVWXZ';
		}
		if ($strength & 2) {
			$vowels .= "AEUY";
		}
		if ($strength & 4) {
			$consonants .= '23456789';
		}
		if ($strength & 8) {
			$consonants .= '@#$%';
		}
	 
		$password = '';
		$alt = time() % 2;
		for ($i = 0; $i < $length; $i++) {
			if ($alt == 1) {
				$password .= $consonants[(rand() % strlen($consonants))];
				$alt = 0;
			} else {
				$password .= $vowels[(rand() % strlen($vowels))];
				$alt = 1;
			}
		}
		return $password;
	}
	
	
		
	/*
	this function used to generate unique order number for cart
	*/
	function generateOrderNumber($length=7, $strength='') 
	{
		$vowels = 'aeuy';
		$consonants = 'bdghjmnpqrstvz';
		if ($strength & 1) {
			$consonants .= 'BDGHJLMNPQRSTVWXZ';
		}
		if ($strength & 2) {
			$vowels .= "AEUY";
		}
		if ($strength & 4) {
			$consonants .= '23456789';
		}
		if ($strength & 8) {
			$consonants .= '@#$%';
		}
	 
		$orderNumber = '';
		$alt = time() % 2;
		for ($i = 0; $i < $length; $i++) {
			if ($alt == 1) {
				$orderNumber .= $consonants[(rand() % strlen($consonants))];
				$alt = 0;
			} else {
				$orderNumber .= $vowels[(rand() % strlen($vowels))];
				$alt = 1;
			}
		}
		return $orderNumber .'-'. time();
	}

	/*
	This SPECIAL function is getting the cart count, called in header.php, Najeeb said on 13 April, 2011
	*/
	function getCartCount($objModel)
	{
		//initializing 
		return $this -> ${objModel} -> _getSingleData('cart', "COUNT(cartID)", "sessionID = '".session_id()."'");
	}
	
/*----------FOR EMAIL SENDING FUNCTIONS HERE-----------------------------------*/


function renderSignupEmail($uName, $uid)
{
	$html = '<html>
			<body style="font-family:Verdana; font-size:14px;">
			Dear '.$uName.'<br />
				
				<p>Your registration has been completed successfully with us. You need to activate your account by click following link.</p>
				
	<a href="'.SITEURL.'?page=register.php&sub=activateMe&buddy='.$uid.'&token='.session_id().'" target="_blank">
	Activate My Account</a>
	<br />
	<br />

	
	Thanks<br />

	Team '.SITEURL.'
	</body>
	</html>';
	
	return $html;
}

function sendMail($pTo, $pSubject, $pMessage, $pFrom = 'admin@shopenv.com')
{
	$headers  = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
    $headers .= "From: $pFrom\r\n";
	
	//echo $pMessage;
	mail($pTo, $pSubject, $pMessage, $headers);
}


	///////////////////////// Pagination //////////////////////////////
	function makePaginationUrl($pageNo){
		$pVar='pgNo';
		$q=explode("&",$_SERVER['QUERY_STRING']);
		$done=false;
		for($i=0;$i<count($q);$i++){
			if(substr($q[$i],0,strlen($pVar)+1)==$pVar."="){
				$q[$i]=$pVar."=".$pageNo;
				$done=true;
				break;
			}
		}
		if($done!=true) $q[]=$pVar."=".$pageNo;
		$q=implode("&",$q);
		return "?".$q;
	}
	
	function makePaginationNext($totalRec){
		if($totalRec==0) return "";
		if(isset($this->data['pgNo'])) $curPage=$this->data['pgNo']; else $curPage=1;
		$tp= ceil($totalRec/$this->totalRows);
		if($curPage!=$tp) return $this->makePaginationUrl($curPage+1); else return "";
	}

	function makePaginationPrevious(){
		if(isset($this->data['pgNo'])) $curPage=$this->data['pgNo']; else $curPage=1;
		if($curPage!=1) return $this->makePaginationUrl($curPage-1); else return "";
	}
	
	function makePaginationCombo($totalRec){
		if($totalRec==0) return "";
		$curPage=$this->data['pgNo'];
		$tp= ceil($totalRec/$this->totalRows);
		$combo="<select onchange='javascript: window.location=this.value;'>";
		for($i=1;$i<=$tp;$i++){
			if($curPage==$i) $sel="selected='selected'"; else $sel="";
			$combo.="<option value='".$this->makePaginationUrl($i)."' $sel>Page $i</option>\n";
		}
		$combo.="</select>";
		return $combo;
	}
	
	function makeLimit(){
		if(isset($this->data['pgNo'])) $pageNo=$this->data['pgNo']; else $pageNo=1;
		$offset=($pageNo-1)*$this->totalRows;
		return " limit $offset,$this->totalRows";
	}
	
	
	function sendEmail($to, $subject, $message, $from = 'admin@gosell.com')
	{

			$this -> loadClass('Email', 'email');

			

			/*$config['protocol'] = 'sendmail';

			$config['mailpath'] = '/usr/sbin/sendmail';*/

			$config['charset'] = 'iso-8859-1';

			$config['wordwrap'] = TRUE;

			$config['mailtype'] = 'html';

			

					

			$this->email->initialize($config);

	

			$this->email->from($from, 'no-reply@sage.com');

			$this->email->to($to);

			//$this->email->cc('another@another-example.com');

			//$this->email->bcc('them@their-example.com');

			

			$this->email->subject($subject);

			$this->email->message($message);

			

			if($this->email->send())		

			{

				//echo $this->email->print_debugger();

				$_SESSION['email_send_status'] .= 'Email sent to '.$to."<br />";

			}

			else

			{

				$_SESSION['email_send_status'] .= 'Email sending failed to '.$to."<br />";

			}

			

		

	}
	
function sendNotifyEmail($to, $subject, $message)

    {

        $html = "<html>
                <body style='font-family:Verdana; font-size:14px;'>
                Hi, <br />
                <p>$message</p>
                <br />
                <br />

                Thanks<br />
                Team ".SITEURL."
                </body>
                </html>";

        $this -> sendEmail($to,$subject,$html);

    }

}

 
?>